<?php


namespace app\controller\api;


use app\BaseController;
use app\common\exception\ApiException;
use app\model\article\ArticleApplyModel;
use app\model\article\ArticleModel;
use app\model\config\RegionModel;
use app\service\utils\QrcodeService;
use think\facade\Cache;
use think\facade\Db;

class TestDriveController extends BaseController
{
    /**
     * 试驾体验列表
     * @return \think\response\Json
     */
    public function getTestDriveList()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $list = ArticleModel::field('id,title,img,num,create_time')
                ->where('type', 2)
                ->order('sort', 'desc')
                ->paginate(['list_row' => $limit, 'page' => $page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 试驾体验详情
     * @return \think\response\Json
     */
    public function getTestDriveDetail()
    {
        try {
            $id = $this->request->param('id');
            $info = ArticleModel::find($id);
            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 省市列表
     * @return \think\response\Json
     */
    public function getCityList()
    {
        try {
            $list = Cache::get('region_list');
            if (!$list) {
                $provinceList = RegionModel::where('pid', 100000)->field('id,name')->select();
                foreach ($provinceList as &$value) {
                    $value['child'] = RegionModel::where('pid', $value['id'])->field('id,name')->select();
                }
                $list = json_encode($provinceList);
                Cache::set('region_list', $list);
            }
            $list = json_decode($list, true);
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 试驾报名
     * @return \think\response\Json
     */
    public function submitTestDriverOrder()
    {
        Db::startTrans();
        try {
            $userId = $this->request->middleware('userId');
            $cityId = $this->request->param('city_id', 0);
            $id = $this->request->param('id', 0);

            $info = ArticleModel::find($id);
            if (!$info) {
                throw new ApiException('信息不存在');
            }
            if ($info->getData('end_time') <= time()) {
                throw new ApiException('活动已结束');
            }
//            $cityIdArr = $info['city_ids'];
//            if ($cityIdArr && !in_array($cityId, $cityIdArr)) {
//                throw new ApiException('该城市暂时不能试驾');
//            }
//            $orderInfo = ArticleApplyModel::where('user_id', $userId)
//                ->where('city_id', $cityId)
//                ->where('status', '<>', 3)
//                ->find();
//            if ($orderInfo) {
//                throw new ApiException('您已经报名过该活动');
//            }
            $info->num = Db::raw("num+1");
            $info->save();

            $orderSn = createOrderSn('article_apply');
//            $qrcodeUrl = QrcodeService::createQrcode(json_encode(['order_sn' => $orderSn, 'type' => 'test_drive']));

            $articleApplyModel = new ArticleApplyModel();
            $articleApplyModel->user_id = $userId;
            $articleApplyModel->article_id = $id;
            $articleApplyModel->city_id = $cityId;
            $articleApplyModel->order_sn = $orderSn;
//            $articleApplyModel->qrcode_url = $qrcodeUrl;
            $articleApplyModel->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 订单列表
     * @return \think\response\Json
     */
    public function getOrderList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $page = $this->request->param('page', 1, 'int');
            $limit = $this->request->param('limit', 10, 'int');
            // 0全部 1待到场 2完成
            $status = $this->request->param('status', 0, 'int');
            $where = [];
            $where[] = ['user_id', '=', $userId];
            if ($status) {
                $where[] = ['status', '=', $status];
            }
            $list = ArticleApplyModel::with(['article', 'city'])
                ->where($where)
                ->order('id', 'asc')
                ->paginate(['list_row' => $limit, 'page' => $page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 试驾详情
     * @return \think\response\Json
     */
    public function detail()
    {
        try {
            $userId = $this->request->middleware('userId');
            $orderId = $this->request->param('order_id', 0, 'int');

            $orderInfo = ArticleApplyModel::with(['article', 'city'])->where('id', $orderId)->where('user_id', $userId)->find();
            if (!$orderInfo) {
                throw new ApiException('非法请求');
            }
            $orderInfo['num'] = ArticleApplyModel::where('article_id', $orderInfo['article_id'])->count();
            return $this->success($orderInfo);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 取消订单
     * @return \think\response\Json
     */
    public function cancel()
    {
        try {
            $userId = $this->request->middleware('userId');
            $orderId = $this->request->param('order_id', 0, 'int');

            $orderInfo = ArticleApplyModel::where('id', $orderId)->where('user_id', $userId)->find();
            if (!$orderInfo) {
                throw new ApiException('非法请求');
            }
            if ($orderInfo['status'] != 1) {
                throw new ApiException('状态错误');
            }
            $orderInfo->status = 3;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 删除订单
     * @return \think\response\Json
     */
    public function del()
    {
        try {
            $userId = $this->request->middleware('userId');
            $orderId = $this->request->param('order_id', 0, 'int');

            $orderInfo = ArticleApplyModel::where('id', $orderId)->where('user_id', $userId)->find();
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            if ($orderInfo['status'] == 1) {
                throw new ApiException('待到场订单不能删除');
            }
            $orderInfo->delete();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}